﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using DXBBS.Components;
using System.Web.Caching;

namespace Cosmetic
{
    public enum EBool
    {
        True,
        False
    }

    public class WebGeneric
    {
        public static string SubString(string aContent, int aLength)
        {
            return aContent.Substring(0, aContent.Length > aLength ? aLength : aContent.Length);
        }
        public static string SubString(string aContent, int aLength, bool isFilterHTML)
        {
            string theResult = aContent.ToString();

            if (isFilterHTML)
            {
                Regex theRegex = new Regex(@"<[^>]+>|]+>");
                theResult = theRegex.Replace(theResult, "");
            }
            return theResult.Substring(0, theResult.Length > aLength ? aLength : theResult.Length);
        }


        /// <summary>
        /// Replace /r/n to html /br
        /// </summary>
        /// <param name="aContent">source content</param>
        /// <returns>Replaced string</returns>
        public static string ToBR(object aContent)
        {
            return aContent.ToString().Replace("\r\n", "</br>");
        }


        public static ForumInfo ReadBBSConfigInfo()
        {
            if (Caches.Read(CacheKey.Config) == null)
            {

                string xmlFile = Servers.MapPath("~/dxbbs/config/Forum.config");
                ForumInfo cacheValue = new ForumInfo();
                using (XmlProvider provider = new XmlProvider(xmlFile))
                {
                    cacheValue.Interface = Convert.ToInt32(provider.ReadAttribute("ForumConfig/Interface", "Value"));
                    cacheValue.DataBase = provider.ReadAttribute("ForumConfig/DataBase", "Value");
                    cacheValue.TimeZone = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TimeZone", "Value"));
                    cacheValue.ForbiddenUploadType = provider.ReadAttribute("ForumConfig/ForbiddenUploadType", "Value");
                    cacheValue.UploadType = provider.ReadAttribute("ForumConfig/UploadType", "Value");
                    cacheValue.TemplatePath = provider.ReadAttribute("ForumConfig/TemplatePath", "Value");
                    cacheValue.SkinPath = provider.ReadAttribute("ForumConfig/SkinPath", "Value");
                    cacheValue.TemplateID = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TemplateID", "Value"));
                    cacheValue.SkinID = Convert.ToInt32(provider.ReadAttribute("ForumConfig/SkinID", "Value"));
                    cacheValue.ForumName = provider.ReadAttribute("ForumConfig/ForumName", "Value");
                    cacheValue.Keyword = provider.ReadAttribute("ForumConfig/Keyword", "Value");
                    cacheValue.Description = provider.ReadAttribute("ForumConfig/Description", "Value");
                    cacheValue.ForumState = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ForumState", "Value"));
                    cacheValue.AllowRegister = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowRegister", "Value"));
                    cacheValue.ShowOnline = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ShowOnline", "Value"));
                    cacheValue.Logo = provider.ReadInnerText("ForumConfig/Logo");
                    cacheValue.Banner = provider.ReadInnerText("ForumConfig/Banner");
                    cacheValue.RefreshTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/RefreshTime", "Value"));
                    cacheValue.ActiveTitleLength = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ActiveTitleLength", "Value"));
                    cacheValue.UserConfirm = Convert.ToInt32(provider.ReadAttribute("ForumConfig/UserConfirm", "Value"));
                    cacheValue.MaxTableCount = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MaxTableCount", "Value"));
                    cacheValue.TablePrefix = provider.ReadAttribute("ForumConfig/TablePrefix", "Value");
                    cacheValue.MalePhoto = provider.ReadAttribute("ForumConfig/MalePhoto", "Value");
                    cacheValue.FemalePhoto = provider.ReadAttribute("ForumConfig/FemalePhoto", "Value");
                    cacheValue.PhotoWidth = Convert.ToInt32(provider.ReadAttribute("ForumConfig/PhotoWidth", "Value"));
                    cacheValue.PhotoHeight = Convert.ToInt32(provider.ReadAttribute("ForumConfig/PhotoHeight", "Value"));
                    cacheValue.MaxPhotoWidth = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MaxPhotoWidth", "Value"));
                    cacheValue.MaxPhotoHeight = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MaxPhotoHeight", "Value"));
                    cacheValue.NickNameLength = Convert.ToInt32(provider.ReadAttribute("ForumConfig/NickNameLength", "Value"));
                    cacheValue.SignLength = Convert.ToInt32(provider.ReadAttribute("ForumConfig/SignLength", "Value"));
                    cacheValue.AllowSignHTML = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowSignHTML", "Value"));
                    cacheValue.AllowSignUBB = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowSignUBB", "Value"));
                    cacheValue.AllowHTML = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowHTML", "Value"));
                    cacheValue.AllowUBB = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowUBB", "Value"));
                    cacheValue.Extension = provider.ReadAttribute("ForumConfig/Extension", "Value");
                    cacheValue.Welcome = Convert.ToInt32(provider.ReadAttribute("ForumConfig/Welcome", "Value"));
                    cacheValue.WelcomeTitle = provider.ReadAttribute("ForumConfig/WelcomeTitle", "Value");
                    cacheValue.WelcomeContent = provider.ReadInnerText("ForumConfig/WelcomeContent");
                    cacheValue.TeamNewsNumber = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TeamNewsNumber", "Value"));
                    cacheValue.TeamPhotoNumber = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TeamPhotoNumber", "Value"));
                    cacheValue.TeamMessageNumber = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TeamMessageNumber", "Value"));
                    cacheValue.SecureKey = provider.ReadAttribute("ForumConfig/SecureKey", "Value");
                    cacheValue.ForbiddenName = provider.ReadAttribute("ForumConfig/ForbiddenName", "Value");
                    cacheValue.CodeType = Convert.ToInt32(provider.ReadAttribute("ForumConfig/CodeType", "Value"));
                    cacheValue.CodeLength = Convert.ToInt32(provider.ReadAttribute("ForumConfig/CodeLength", "Value"));
                    cacheValue.CodeDot = Convert.ToInt32(provider.ReadAttribute("ForumConfig/CodeDot", "Value"));
                    cacheValue.LoginCode = Convert.ToInt32(provider.ReadAttribute("ForumConfig/LoginCode", "Value"));
                    cacheValue.RegisterCode = Convert.ToInt32(provider.ReadAttribute("ForumConfig/RegisterCode", "Value"));
                    cacheValue.TopicCode = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicCode", "Value"));
                    cacheValue.ReplyCode = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyCode", "Value"));
                    cacheValue.MessageCode = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MessageCode", "Value"));
                    cacheValue.TopicTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicTime", "Value"));
                    cacheValue.ReplyTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyTime", "Value"));
                    cacheValue.TopicPerTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicPerTime", "Value"));
                    cacheValue.ReplyPerTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyPerTime", "Value"));
                    cacheValue.MessagePerTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MessagePerTime", "Value"));
                    cacheValue.RegisterPerTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/RegisterPerTime", "Value"));
                    cacheValue.LoginPerTime = Convert.ToInt32(provider.ReadAttribute("ForumConfig/LoginPerTime", "Value"));
                    cacheValue.AllowUploadFile = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowUploadFile", "Value"));
                    cacheValue.AllowUploadFace = Convert.ToInt32(provider.ReadAttribute("ForumConfig/AllowUploadFace", "Value"));
                    cacheValue.FileUploadPath = provider.ReadAttribute("ForumConfig/FileUploadPath", "Value");
                    cacheValue.FaceUploadPath = provider.ReadAttribute("ForumConfig/FaceUploadPath", "Value");
                    cacheValue.TeamUploadPath = provider.ReadAttribute("ForumConfig/TeamUploadPath", "Value");
                    cacheValue.TeamUploadSize = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TeamUploadSize", "Value"));
                    cacheValue.FileNameType = Convert.ToInt32(provider.ReadAttribute("ForumConfig/FileNameType", "Value"));
                    cacheValue.OuterFace = Convert.ToInt32(provider.ReadAttribute("ForumConfig/OuterFace", "Value"));
                    cacheValue.FaceUploadCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/FaceUploadCoin", "Value"));
                    cacheValue.FaceUploadPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/FaceUploadPoint", "Value"));
                    cacheValue.FileUploadCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/FileUploadCoin", "Value"));
                    cacheValue.FileUploadPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/FileUploadPoint", "Value"));
                    cacheValue.RegisterCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/RegisterCoin", "Value"));
                    cacheValue.RegisterPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/RegisterPoint", "Value"));
                    cacheValue.LoginCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/LoginCoin", "Value"));
                    cacheValue.LoginPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/LoginPoint", "Value"));
                    cacheValue.TopicCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicCoin", "Value"));
                    cacheValue.TopicPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicPoint", "Value"));
                    cacheValue.ReplyCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyCoin", "Value"));
                    cacheValue.ReplyPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyPoint", "Value"));
                    cacheValue.GoodCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/GoodCoin", "Value"));
                    cacheValue.GoodPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/GoodPoint", "Value"));
                    cacheValue.TopicDelCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicDelCoin", "Value"));
                    cacheValue.TopicDelPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TopicDelPoint", "Value"));
                    cacheValue.ReplyDelCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyDelCoin", "Value"));
                    cacheValue.ReplyDelPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ReplyDelPoint", "Value"));
                    cacheValue.DownloadCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/DownloadCoin", "Value"));
                    cacheValue.DownloadPoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/DownloadPoint", "Value"));
                    cacheValue.MessageCoin = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MessageCoin", "Value"));
                    cacheValue.MessagePoint = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MessagePoint", "Value"));
                    cacheValue.WaterType = Convert.ToInt32(provider.ReadAttribute("ForumConfig/WaterType", "Value"));
                    cacheValue.WaterPossition = Convert.ToInt32(provider.ReadAttribute("ForumConfig/WaterPossition", "Value"));
                    cacheValue.TextContent = provider.ReadAttribute("ForumConfig/TextContent", "Value");
                    cacheValue.TextFont = provider.ReadAttribute("ForumConfig/TextFont", "Value");
                    cacheValue.TextSize = Convert.ToInt32(provider.ReadAttribute("ForumConfig/TextSize", "Value"));
                    cacheValue.TextColor = provider.ReadAttribute("ForumConfig/TextColor", "Value");
                    cacheValue.ImageFile = provider.ReadAttribute("ForumConfig/ImageFile", "Value");
                    cacheValue.ShowMenu = Convert.ToInt32(provider.ReadAttribute("ForumConfig/ShowMenu", "Value"));
                    cacheValue.PasswordType = Convert.ToInt32(provider.ReadAttribute("ForumConfig/PasswordType", "Value"));
                    cacheValue.MinUsernameLength = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MinUsernameLength", "Value"));
                    cacheValue.MaxUsernameLength = Convert.ToInt32(provider.ReadAttribute("ForumConfig/MaxUsernameLength", "Value"));
                }
                CacheDependency cd = new CacheDependency(xmlFile);
                Caches.Write(CacheKey.Config, cacheValue, cd);
            }

            return (ForumInfo)Caches.Read(CacheKey.Config);

        }

        public static string ChineseTime(object aTime)
        {
            return Convert.ToDateTime(aTime.ToString()).ToString(new System.Globalization.CultureInfo("zh-CN"));
        }

        public static string ShortTime(object aTime)
        {
            return Convert.ToDateTime(aTime.ToString()).ToShortDateString();
        }

        public static string ChineseShortTime(object aTime)
        {
            DateTime theTime = Convert.ToDateTime(aTime.ToString());
            return String.Format("{0}/{1}/{2}", theTime.Year, theTime.Month, theTime.Day);
        }

        public static string Price(object aPrice)
        {
            return "￥" + aPrice.ToString().Remove(aPrice.ToString().Length - 2);
        }
        public static string MarketPrice(object aPrice)
        {
            return "￥" + (Convert.ToDecimal(aPrice.ToString()) * 1.5m).ToString().Remove(aPrice.ToString().Length - 2);
        }


        public static void WebMessageBox(string aMessage, Control aControl)
        {
            string theKey = "WebMessageBox" + DateTime.Now.ToString();
            string theScript = String.Format("alert('{0}');", aMessage);
            if (aControl is UpdatePanel)
            {
                ScriptManager.RegisterClientScriptBlock(aControl, aControl.GetType(), theKey, theScript, true);
            }
            else if (aControl is Page)
            {
                (aControl as Page).ClientScript.RegisterStartupScript(aControl.GetType(), theKey, theScript, true);
            }
        }

        public static string SmallImage(string aImageUrl)
        {
            //原图地址错误
            if (aImageUrl.LastIndexOf('.')<0)
            {
                return aImageUrl;
            }
            //原图不存在
            if (!File.Exists(HttpContext.Current.Server.MapPath(aImageUrl)))
            {
                return aImageUrl;
            }
            string newImageUrl = aImageUrl.Insert(aImageUrl.LastIndexOf('.'),"_s");
            //缩略图已存在
            if(File.Exists(HttpContext.Current.Server.MapPath(newImageUrl)))
            {
                return newImageUrl;
            }
            Bitmap theBitmap = new Bitmap(HttpContext.Current.Server.MapPath(aImageUrl));
            int theWidth = theBitmap.Width;
            int theHeight = theBitmap.Height;
            Rectangle cloneRect;
            if (theHeight < theWidth)
            {
                cloneRect = new Rectangle((theWidth - theHeight) / 2, 0, theHeight, theHeight);
            }
            else
            {
                cloneRect = new Rectangle(0, (theHeight - theWidth) / 2, theWidth, theWidth);
            }

            //   Clone   a   portion   of   the   Bitmap   object.  
            PixelFormat format = theBitmap.PixelFormat;
            Bitmap newBitmap = theBitmap.Clone(cloneRect, format);
            //   Draw   the   cloned   portion   of   the   Bitmap   object.  
            switch (aImageUrl.Substring(aImageUrl.LastIndexOf('.')).ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    newBitmap.Save(HttpContext.Current.Server.MapPath(newImageUrl), ImageFormat.Jpeg);
                    break;
                case ".gif":
                    newBitmap.Save(HttpContext.Current.Server.MapPath(newImageUrl), ImageFormat.Gif);
                    break;
            }

            return newImageUrl;
        }


        /// <summary>
        /// 根据日期返回星座
        /// </summary>
        /// <param name="aDate">需要查询星座的日期</param>
        /// <returns>星座</returns>
        public static string Constellation(DateTime aDate)
        {
            int theDateNum = 0;

            if (aDate.Month == 1 && aDate.Day < 20)
            {
                if (aDate.Day < 10)
                {
                    theDateNum = int.Parse(string.Format("130{0}", aDate.Day));
                }
                else
                {
                    theDateNum = int.Parse(string.Format("13{0}", aDate.Day));
                }
            }
            else
            {
                if (aDate.Day < 10)
                {
                    theDateNum = int.Parse(string.Format("{0}0{1}", aDate.Month, aDate.Day));
                }
                else
                {
                    theDateNum = int.Parse(string.Format("{0}{1}", aDate.Month, aDate.Day));
                }
            }
            int[] theConstellationBound = { 120, 220, 321, 421, 521, 622, 723, 823, 923, 1023, 1121, 1222, 1320 };
            string[] theConstellations = { "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座" };


            for (int i = 0; i < theConstellationBound.Length - 1; i++)
            {
                if (theConstellationBound[i] <= theDateNum && theConstellationBound[i + 1] > theDateNum)
                {
                    return theConstellations[i];
                }
            }
            return "靠！外星人啊。";
        }
    }

    /// <summary>
    /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
    /// </summary>
    public class AliPay
    {
        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
        public static string GetMD5(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 冒泡排序法
        /// </summary>
        public static string[] BubbleSort(string[] r)
        {
            int i, j; //交换标志 
            string temp;

            bool exchange;

            for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前，交换标志应为假

                for (j = r.Length - 2; j >= i; j--)
                {
                    if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)　//交换条件
                    {
                        temp = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = temp;

                        exchange = true; //发生了交换，故将交换标志置为真 
                    }
                }

                if (!exchange) //本趟排序未发生交换，提前终止算法 
                {
                    break;
                }
            }
            return r;
        }

        public static string CreatUrl(
            string gateway,
            string service,
            string partner,
            string sign_type,
            string out_trade_no,
            string subject,
            string body,
            string total_fee,
            string show_url,
            string seller_email,
            string key,
            string return_url,
            string _input_charset,
            string notify_url,
            string logistics_type,
            string logistics_fee,
            string logistics_payment,
            string logistics_type_1,
            string logistics_fee_1,
            string logistics_payment_1,
            string logistics_type_2,
            string logistics_fee_2,
            string logistics_payment_2,
            string quantity
            )
        {
            /// <summary>
            /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
            /// </summary>
            int i;

            //构造数组；
            string[] Oristr ={ 
                "service="+service, 
                "partner=" + partner, 
                "subject=" + subject, 
                "body=" + body, 
                "out_trade_no=" + out_trade_no, 
                "price=" + total_fee, 
                "show_url=" + show_url,  
                "payment_type=1", 
                "seller_email=" + seller_email, 
                "notify_url=" + notify_url,
                "_input_charset="+_input_charset,          
                "return_url=" + return_url,
                "quantity="+quantity,
                "logistics_type="+logistics_type,
                "logistics_fee="+logistics_fee ,
                "logistics_payment="+logistics_payment,
	            "logistics_type_1="+logistics_type_1,
                "logistics_fee_1="+logistics_fee_1,
                "logistics_payment_1="+logistics_payment_1,
	            "logistics_type_2="+logistics_type_2,
                "logistics_fee_2="+logistics_fee_2,
                "logistics_payment_2="+logistics_payment_2
                };

            //进行排序；
            string[] Sortedstr = BubbleSort(Oristr);


            //构造待md5摘要字符串 ；

            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr[i]);

                }
                else
                {

                    prestr.Append(Sortedstr[i] + "&");
                }

            }

            prestr.Append(key);

            //生成Md5摘要；
            string sign = GetMD5(prestr.ToString(), _input_charset);

            //构造支付Url；
            char[] delimiterChars = { '=' };
            StringBuilder parameter = new StringBuilder();
            parameter.Append(gateway);
            for (i = 0; i < Sortedstr.Length; i++)
            {

                parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
            }

            parameter.Append("sign=" + sign + "&sign_type=" + sign_type);

            //返回支付Url；
            return parameter.ToString();

        }

        public static string CreatUrl(
                string gateway,
                string service,
                string partner,
                string sign_type,
                string out_trade_no,
                string subject,
                string body,
                string total_fee,
                string show_url,
                string seller_email,
                string key,
                string return_url,
                string _input_charset,
                string notify_url)
        {
            /// <summary>
            /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
            /// </summary>
            int i;

            //构造数组；
            string[] Oristr ={ 
                "service="+service, 
                "partner=" + partner, 
                "subject=" + subject, 
                "body=" + body, 
                "out_trade_no=" + out_trade_no, 
                "total_fee=" + total_fee, 
                "show_url=" + show_url,  
                "payment_type=1", 
                "seller_email=" + seller_email, 
                "notify_url=" + notify_url,
                "_input_charset="+_input_charset,          
                "return_url=" + return_url
                };

            //进行排序；
            string[] Sortedstr = BubbleSort(Oristr);


            //构造待md5摘要字符串 ；

            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr[i]);

                }
                else
                {

                    prestr.Append(Sortedstr[i] + "&");
                }

            }

            prestr.Append(key);

            //生成Md5摘要；
            string sign = GetMD5(prestr.ToString(), _input_charset);

            //构造支付Url；
            char[] delimiterChars = { '=' };
            StringBuilder parameter = new StringBuilder();
            parameter.Append(gateway);
            for (i = 0; i < Sortedstr.Length; i++)
            {

                parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
            }

            parameter.Append("sign=" + sign + "&sign_type=" + sign_type);

            //返回支付Url；
            return parameter.ToString();

        }

        /// <summary>
        /// version 3 no notify_URL
        /// </summary>
        /// <param name="gateway"></param>
        /// <param name="service"></param>
        /// <param name="partner"></param>
        /// <param name="sign_type"></param>
        /// <param name="out_trade_no"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="total_fee"></param>
        /// <param name="show_url"></param>
        /// <param name="seller_email"></param>
        /// <param name="key"></param>
        /// <param name="return_url"></param>
        /// <param name="_input_charset"></param>
        /// <returns></returns>
        public static string CreatUrl(
        string gateway,
        string service,
        string partner,
        string sign_type,
        string out_trade_no,
        string subject,
        string body,
        string total_fee,
        string show_url,
        string seller_email,
        string key,
        string return_url,
        string _input_charset
            )
        {
            /// <summary>
            /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
            /// </summary>
            int i;

            //构造数组；
            string[] Oristr ={ 
                "service="+service, 
                "partner=" + partner, 
                "subject=" + subject, 
                "body=" + body, 
                "out_trade_no=" + out_trade_no, 
                "total_fee=" + total_fee, 
                "show_url=" + show_url,  
                "payment_type=1", 
                "seller_email=" + seller_email,
                "_input_charset="+_input_charset,          
                "return_url=" + return_url
                };

            //进行排序；
            string[] Sortedstr = BubbleSort(Oristr);


            //构造待md5摘要字符串 ；

            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr[i]);

                }
                else
                {

                    prestr.Append(Sortedstr[i] + "&");
                }

            }

            prestr.Append(key);

            //生成Md5摘要；
            string sign = GetMD5(prestr.ToString(), _input_charset);

            //构造支付Url；
            char[] delimiterChars = { '=' };
            StringBuilder parameter = new StringBuilder();
            parameter.Append(gateway);
            for (i = 0; i < Sortedstr.Length; i++)
            {

                parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
            }

            parameter.Append("sign=" + sign + "&sign_type=" + sign_type);

            //返回支付Url；
            return parameter.ToString();

        }

    }

    public class ChinaPay
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MerId">MerId为ChinaPay统一分配给商户的商户号，15位长度，必填</param>
        /// <param name="OrdId">商户提交给ChinaPay的交易订单号，16位长度，必填</param>
        /// <param name="TransAmt">订单交易金额，12位长度，左补0，必填,单位为分</param>
        /// <param name="CuryId">订单交易币种，3位长度，固定为人民币156，必填</param>
        /// <param name="TransDate">订单交易币种，3位长度，固定为人民币156，必填</param>
        /// <param name="TransType">交易类型，4位长度，必填</param>
        /// <param name="Version">支付接入版本号，必填</param>
        /// <param name="BgRetUrl">后台交易接收URL，长度不要超过80个字节，必填</param>
        /// <param name="PageRetUrl">页面交易接收URL，长度不要超过80个字节，必填</param>
        /// <param name="GateId">支付网关号，可选</param>
        /// <param name="Priv1">商户私有域，长度不要超过60个字节</param>
        /// <param name="ChkValue">256字节长的ASCII码,为此次交易提交关键数据的数字签名，必填</param>
        /// <returns></returns>
        public static string CreatUrl(
                string GateWay,
                string MerId,
                string OrdId,
                string TransAmt,
                string CuryId,
                string TransDate,
                string TransType,
                string Version,
                string BgRetUrl,
                string PageRetUrl,
                string GateId,
                string Priv1,
                string ChkValue)
        {
            StringBuilder url = new StringBuilder();
            url.Append(GateWay);
            url.Append("&MerId=" + MerId);
            url.Append("&OrdId=" + OrdId);
            url.Append("&TransAmt=" + TransAmt);
            url.Append("&CuryId=" + CuryId);
            url.Append("&TransDate=" + TransDate);
            url.Append("&TransType=" + TransType);
            url.Append("&Version=" + Version);
            url.Append("&BgRetUrl=" + BgRetUrl);
            url.Append("&PageRetUrl=" + PageRetUrl);
            url.Append("&GateId=" + GateId);
            url.Append("&Priv1=" + Priv1);
            url.Append("&ChkValue=" + ChkValue);
            return url.ToString();
        }
    }
}